import { includes, reduce, get } from 'lodash-es'
import { PERMISSION_LIST } from '@/utils/permission/permission-list'
// import customerManageRoute from '@/router/customer-manage'
import { createActions, handleMutations } from '@axios'
import api from '@/api/corp-manage'
import * as actionTypes from '../actions/corp-manage'
  
/****
 * 用户数据
 ****/

const module = {
  namespaced: true,
  state: {
    userInfo: {},
    menuList: {},
    buttonList: {},
    buttonRoles: [],
    currentDeptId: null, // 当前数据范围部门Id
    currentDeptName: '', // 当前选择部门名称
    currentDeptLevel: '', // 当前部门层级
    currentDept: {
      id: '',
      label: '',
      level: '',
    }
  },
  getters: {
    permissionMap(state) {
      return reduce(
        PERMISSION_LIST,
        (prev, key) => ({
          ...prev,
          // 管理员默认有权限
          [key]: includes(get(state.userInfo, 'permissionList', []), key),
        }),
        {}
      )
    },

    /**
     * 管理员角色
     * @param state
     * @return {boolean}
     */
    adminRole(state) {
      return get(state.userInfo, 'mgrFlag', 0) !== 0
    },
    // 是对公领域
    isPublic (state) {
      return ['BUSINESS', 'SETTLEMENT'].includes(state.userInfo?.domainType)
    },
    // 是普惠
    isBusiness (state) {
      return state.userInfo?.domainType === 'BUSINESS'
    }
  },
  mutations: {
    ...handleMutations({
      [actionTypes.SET_USER_MENU_LIST]: {
        success (state, payload) {
          console.log('payload:', payload)
          const { menu } = payload
          if (menu) {
            state.menuList = menu
          }
        }
      },
      [actionTypes.SET_BUTTON_LIST]: {
        success (state, payload) {
          state.buttonList = payload
          const buttonRoles = []
          for (const item of payload) {
            if (item.resources) {
              buttonRoles.push(item.resources)
            }
          }
          state.buttonRoles = buttonRoles
        }
      }
    }),
    updateUserInfo(state, data) {
      state.userInfo = data
    },
    updateMenuList(state, menu) {
      state.menuList = menu
    },
    updateDeptId(state, deptId) {
      state.currentDeptId = deptId
    },
    updateDeptName(state, deptName) {
      state.currentDeptName = deptName
    },
    updateDeptLevel(state, deptLevel) {
      state.currentDeptLevel = deptLevel
    },
    updateDeptObj(state, deptObj) {
      const { deptId, deptName, deptLevel } = deptObj
      state.currentDeptId = deptId
      state.currentDeptName = deptName
      state.currentDeptLevel = deptLevel
      state.currentDept.id = deptId
      state.currentDept.label = deptName
      state.currentDept.level = deptLevel
    },
  },
  actions: createActions({
    ...api
  }),
}

export default module
